package com.eternal.base.data.ble;

import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

public abstract class BaseParse<T> implements ObservableOnSubscribe<T> {
    protected byte[] now;
    protected byte[] last;
    protected int total = -1;
    protected int i;

    public void setNow(byte[] now) {
        this.now = now;
    }

    public boolean isEnd() {
        return total == -1;
    }

    @Override
    public void subscribe(ObservableEmitter<T> emitter) throws Exception {
        if (last != null) {
            byte[] temp = new byte[now.length + last.length];
            System.arraycopy(last, 0, temp, 0, last.length);
            System.arraycopy(now, 0, temp, last.length, now.length);
            now = temp;
            last = null;
        }
        i = 0;
        if (total == -1) {
            init();
        }
        while (checkLength()) {
            emitter.onNext(parse());
        }
        if (total == 0) {
            total = -1;
        } else if (i < now.length) {
            last = new byte[now.length - i];
            System.arraycopy(now, i, last, 0, last.length);
        }
        emitter.onComplete();
    }

    abstract boolean checkLength();

    abstract T parse();

    abstract void init();
}
